package vn.axonactive.devday.jsf.session1;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 * Explain:
 * 
 * * A managed bean is generally a java bean with its life-cycle been managed by
 *   the server. i.e. the server is responible for constructing and destructing an
 *   instance. 
 * * That's also the reason why you have to specify a scope. 
 * * In JSF applications, you use managed beans for all data that needs to be accessible
 *   from a page. The beans are the connection between the user interface and the
 *   backend of the application.
 * * Explain the scopes 
 */

@ManagedBean(name = "user")
//@RequestScoped
//@ViewScoped
@SessionScoped
//@ApplicationScoped
public class UserBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name;
	private String pass;
	private String salutation;
	private String[] spokenLanguageCodes;
	private Date creationDate; 
	
	@PostConstruct
	public void init() {
		this.creationDate = new Date();
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public boolean isNameDefined() {
		return name != null && name.trim().length() > 0;
	}

	public String getSalutation() {
		return salutation;
	}

	public void setSalutation(String salutation) {
		this.salutation = salutation;
	}

	public String[] getSpokenLanguageCodes() {
		return spokenLanguageCodes;
	}
	
	public Date getCreationDate() {
		return this.creationDate;
	}

	public void setSpokenLanguageCodes(String[] spokenLanguageCodes) {
		this.spokenLanguageCodes = spokenLanguageCodes;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public List<Language> getLanguages() {
		List<Language> languages = new ArrayList<Language>();

		languages.add(new Language("en", "English"));
		languages.add(new Language("vn", "Vietnamese"));
		languages.add(new Language("de", "German"));
		languages.add(new Language("fr", "French"));
		languages.add(new Language("it", "Italian"));

		return languages;
	}

	public String login() {
		if (getPass().equals("pass")) {
			return "welcome";
		} else {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Invalid user or pass"));
			return null;
		}
	}
	
}
